import userService from "@/apis/user";
import orderService from "@/apis/order";

// app.js
const accountInfo = wx.getAccountInfoSync();
const isTrial = accountInfo.miniProgram.envVersion === 'trial'; // 体验版环境

// if (isTrial) {
//   const vConsole = new VConsole();
//   console.log('vConsole 已启用，当前环境：体验版');
// }

// app.js
App({
  onLaunch() {
    console.log("app.js onLaunch()");
    // 初始化全局录音管理器
    const rm=wx.getRecorderManager();
    this.globalData.recorderManager = rm;
    const gd=this.globalData;
    console.log("rm注册onStart")
    rm.onStart(() => {
      gd.isRecording = true;
      console.log('onStart()录音开始');
    })
    console.log("rm注册onStop")
    rm.onStop(res => {
      gd.isRecording = false;
      console.log('onStop()录音结束');
      //显示加载中
      wx.showLoading({
        title: '录音上传中',
      });
      orderService.upload_record(res.tempFilePath).then(res => {
        console.log(res)
        //隐藏加载中
        wx.hideLoading();
      })
    })
    console.log("rm注册onError")
    rm.onError(err => {
      gd.isRecording = false;
      console.log('onError()录音出错', err);
      //显示加载中
      wx.showLoading({
        title: '录音上传中',
      });
      orderService.upload_record(rm.tempFilePath).then(res => {
        console.log(res)
        //隐藏加载中
        wx.hideLoading();
      })
    })
},

  onShow() {
    
  },
  globalData: {
    avatarUrl: '/assets/imgs/user-unlogin.png',
    userInfo: null,
    order:{
    },
    isRecording: false,
    recorderManager: null
  },
  checkToken: async function() {
    const token = wx.getStorageSync('access_token');
    if (!token) return false;

    try {
        const payloadBase64 = token.split('.')[1];
        // 添加Base64补全（=号填充）
        const padded = payloadBase64 + '='.repeat((4 - payloadBase64.length % 4) % 4);
        
        // 转换为标准Base64
        const standardBase64 = padded
          .replace(/-/g, '+')
          .replace(/_/g, '/');

        // 使用小程序的API转换
        const arrayBuffer = wx.base64ToArrayBuffer(standardBase64);
        
        // 正确转换为UTF-8字符串
        const payloadStr = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        const payload = JSON.parse(payloadStr); // 这里之前出错
        
        // 计算剩余时间（分钟）
        const remainMinutes = (payload.exp * 1000 - Date.now()) / 1000 / 60;

        const res = await userService.self();
        const app = getApp()
        app.globalData.userInfo = res.data.data;
        
        // 自动续期逻辑
        if (remainMinutes < 5) {
            const res = await http.request({
                url: API.login.refresh,
                method: 'POST',
                data: {
                    refresh_token: wx.getStorageSync('refresh_token')
                }
            });
            
            wx.setStorageSync('access_token', res.data.access_token);
            wx.setStorageSync('refresh_token', res.data.refresh_token);
        }else if (payload.exp * 1000 < Date.now()) {
          this.clearAuthAndRedirect(); // 这里会触发跳转
          return false;
        }
        
        return true;
    } catch (e) {
        console.error('Token验证失败:', e);
        this.clearAuthAndRedirect();
        return false;
    }
  },
  clearAuthAndRedirect() {
    wx.removeStorageSync('access_token');
    wx.removeStorageSync('refresh_token');
    wx.reLaunch({
      url: '/pages/login/login'
    });
  }
})
